//
//  QRViewController.m
//  QRCode
//
//  Created by 蔡万鸿 on 15/7/11.
//  Copyright (c) 2015年 黄花菜. All rights reserved.
//

#import "QRViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface QRViewController ()<AVCaptureMetadataOutputObjectsDelegate>
//冲击波顶部约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;
//扫描框容器视图高度约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;
// 会话
@property (nonatomic, strong) AVCaptureSession *session;
@end

@implementation QRViewController

- (void)viewDidLoad {
    [super viewDidLoad];
 
    //Video 扫描录像
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //输入设备 (麦克风/摄像头)
    AVCaptureDeviceInput *inputDevice = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];
    
    //输出 (告诉你结果)
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //捕获Session
    AVCaptureSession *sesson = [[AVCaptureSession alloc] init];
    self.session = sesson;
    
    
#warning 需要往session添加输入输出
    //给session添加输入设备,输入设备不能重复添加
    if ([sesson canAddInput:inputDevice]) {
        [sesson addInput:inputDevice];
    }
    
    //给session添加输出
    if ([sesson canAddOutput:output]) {
        [sesson addOutput:output];
    }
    
    
    //metadataObjectTypes
#warning 扫描的时候，要设置 输出的类型（二维码）,这个方法调用要在 session添加到输入输出之后
    
    //设置二维码
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    // AVMetadataObjectTypeUPCECode
    //系统扫描是用图层
    AVCaptureVideoPreviewLayer *captureLayer = [AVCaptureVideoPreviewLayer layerWithSession:sesson];
    
    //设置图层frm
    captureLayer.frame = self.view.bounds;
    
    //把扫描的图片添加到控制器view的图层
    //[self.view.layer addSublayer:captureLayer];
    
    [self.view.layer insertSublayer:captureLayer atIndex:0];
    
#warning 扫描通过会话
    //开始扫描
    [sesson startRunning];

}

#pragma mark 扫描结果
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{

    if (metadataObjects.count > 0) {
 
        //扫描到结果，要停止扫描
        [self.session stopRunning];
        
        //获取结果
        for (AVMetadataObject *obj  in metadataObjects) {
            
            NSLog(@"%@",obj);
        }
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self barAnimation];
}

//冲击波动画
- (void)barAnimation {
    
    //设置初始约束
    self.topConstraint.constant = -self.heightConstraint.constant;
    //强制更新布局
    [self.view layoutIfNeeded];

    [UIView animateWithDuration:2.0 animations:^{
        //设置动画重复次数，一定要在内部
        [UIView setAnimationRepeatCount:MAXFLOAT];
        
        self.topConstraint.constant = self.heightConstraint.constant;
        [self.view layoutIfNeeded];
        
    }];
}

@end
